#include "FormWin32.hpp"

namespace Gui
{
    /*
        El procedimiento de ventana.
    */
	LRESULT CALLBACK FormWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
	{
	    ControlWin32* Ctrl;
        
        Ctrl = ControlWin32::GetControl(hWnd);
	    
	    if (Ctrl == NULL)
            return DefWindowProc(hWnd, Msg, wParam, lParam);
	    
		switch (Msg)
		{
			case WM_CLOSE:
			{
			    FormWin32* Frm;
			    
			    Frm = dynamic_cast<FormWin32*>(Ctrl);
                Frm->GetCloseEvent()->Raise(NULL, NULL);
                
                PostQuitMessage(0);
			 
				break;
			}

			case WM_SIZE:
			{
                Size2<uint> Size;

                Size.Width = LOWORD(lParam);
                Size.Height = HIWORD(lParam);

                Ctrl->GetSizeEvent()->Raise(NULL, &Size);
                
				break;
			}

		default:
			return DefWindowProc(hWnd, Msg, wParam, lParam);
		}

		return 0;
	};


	FormWin32::FormWin32(const std::string &Text, const Size2<int> &Size)
	{
		WNDCLASS wc;
		DWORD Width, Height;

        ControlWin32::m_hWnd = NULL;

        Width = static_cast<DWORD>(Size.Width);
        Height = static_cast<DWORD>(Size.Height);

		memset( &wc, 0, sizeof(wc) );

		//Registrar la clase
		wc.lpfnWndProc = FormWndProc;
		wc.lpszClassName = "RevEng::FormWin32";
		wc.hInstance = GetModuleHandle(NULL);
		wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
		wc.hCursor = LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

		RegisterClass(&wc);

		//Crear la ventana
		if (Width < 0)
            Width = 400;

        if (Height < 0)
            Height = 300;

		ControlWin32::m_hWnd = CreateWindow("RevEng::FormWin32", Text.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, Width, Height, NULL, NULL, wc.hInstance, NULL);

		//
		if (ControlWin32::m_hWnd)
			ControlWin32::AddControl(m_hWnd, this);
	}
	

	bool FormWin32::DoEvents()
	{
		MSG Msg;
		bool Result;

		if (GetMessage(&Msg, m_hWnd, 0, 0) == TRUE)
		{
			TranslateMessage(&Msg);
			DispatchMessage(&Msg);

			Result = true;
		}
		else
			Result = false;

		return Result;
	}
}
